//
//  XQBaseSendMessageButton.m
//  JoinPeso
//
//  Created by 小琦 on 2024/11/20.
//

#import "XQBaseSendMessageButton.h"

@interface XQBaseSendMessageButton()
{
    NSString *_originTitle;
}
@property (nonatomic, strong) NSTimer  *timer;
@property (nonatomic, assign) long timestamp;
@property (nonatomic, assign) BOOL isCountDown;
@end


@implementation XQBaseSendMessageButton

- (void)start {
    self.enabled = NO;
    self.timestamp = 60;
    _originTitle = self.titleLabel.text;
    NSString *str = [NSString stringWithFormat:@"%lds", self.timestamp];
    [self setTitle:str forState:UIControlStateNormal];
    [self setTitle:str forState:UIControlStateDisabled];

    // 清空定时器
    [self stopTimer];
    self.isCountDown = YES;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changeTitle) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)startWithTime:(NSInteger)time {
    self.enabled = NO;
    self.timestamp = time;
    _originTitle = self.titleLabel.text;
    NSString *str = [NSString stringWithFormat:@"%lds", self.timestamp];
    [self setTitle:str forState:UIControlStateNormal];
    [self setTitle:str forState:UIControlStateDisabled];
    
    // 清空定时器
    [self stopTimer];
    self.isCountDown = YES;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changeTitle) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)changeTitle {
    if (self.timestamp == 1) {
        [self setTitle:@"retry" forState:UIControlStateNormal];
        [self setTitle:@"retry" forState:UIControlStateDisabled];
        self.timestamp = 60;
        [self stopTimer];
        self.isCountDown = NO;
        self.enabled = YES;
    }
    else {
        self.timestamp--;
        NSString *str = [NSString stringWithFormat:@"%lds", self.timestamp];
        [self setTitle:str forState:UIControlStateNormal];
        [self setTitle:str forState:UIControlStateDisabled];
    }
}

- (void)stopTimer {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)stop {
    // 先停止timer
    [self stopTimer];
    self.timestamp = 60;
    self.enabled = YES;
    self.isCountDown = NO;
    [self setTitle:_originTitle forState:UIControlStateNormal];
}

@end
